import json
import os
from urllib.request import urlretrieve

# 下载list资源
types = [{"value": "1", "desc": "课本"}, {"value": "3", "desc": "课外读物"}]
listFilePath = "bookList_{}.json"
listResourcePath = "resource/cover_{}/"
newListFilePath = "use_bookList_{}.json"

for ind, type in enumerate(types):
    originFile = open(listFilePath.format(type['value']), mode='r')
    originData = json.loads(originFile.read())
    if not os.path.exists(listResourcePath.format(type['value'])):
        os.makedirs(listResourcePath.format(type['value']))
    for ind, bookInfo in enumerate(originData['data']):
        coverImageUrl = bookInfo['cover_image_url']
        resourcePaths = coverImageUrl.split('/')
        coverImageName = resourcePaths[len(resourcePaths) - 1]
        newImagePath = listResourcePath.format(type['value']) + '/' + coverImageName
        try:
            urlretrieve(coverImageUrl, newImagePath)
        except BaseException:
            print("下载图片失败：" + coverImageUrl)
            urlretrieve(coverImageUrl.replace(" ", "%20"), newImagePath)
        bookInfo['cover_image_url_local'] = newImagePath
        bookInfo['is_download'] = 0
    newFile = open(newListFilePath.format(type['value']), mode='w')
    print(json.dumps(originData, ensure_ascii=False), file=newFile)
